import { ListRowState } from '../../types'

interface CarState {
	carList: CarListRowState[]
}

interface CarListRowState extends ListRowState {
	count: number
	isChecked: boolean
}

const initState: CarState = {
	carList: []
}


export const carReducer = (state = initState, action: any): CarState => {
	switch (action.type) {
		case 'addCar': {
			// 1. 查找购物车数据
			const item = state.carList.find(v => v.id === action.payload.id)

			if (item) {
				// 找到了
				item.count++
			} else {
				// 没找到
				state.carList.push({ ...action.payload, isChecked: false, count: 1 })
			}

			return {
				...state,
				carList: [...state.carList]
			}
		}
		case 'subCar': {
			// 1. 查找购物车数据
			const item = state.carList.find(v => v.id === action.payload.id)

			if (item) {
				// 找到了
				item.count--
			}

			return {
				...state,
				carList: [...state.carList]
			}
		}
		case 'deleteCar': {
			return {
				...state,
				carList: state.carList.filter(v => v.id !== action.payload.id)
			}
		}
		case 'switchCar': {
			// 1. 查找购物车数据
			const item = state.carList.find(v => v.id === action.payload.id)

			if (item) {
				// 找到了
				item.isChecked = !item.isChecked
			}

			return {
				...state,
				carList: [...state.carList]
			}

		}
		case 'switchAllCar': {
			state.carList.forEach(v => v.isChecked = action.payload);
			return {
				...state,
				carList: [...state.carList]
			}
		}
	}

	return state
}